<?php

namespace App\Console\Commands;

use App\Models\EasyWechat;
use App\Models\MyWechatUpload;
use App\Models\Order;
use Illuminate\Console\Command;

class UpdateOrderStatus extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'make:update_order_status';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        Order::query()
            ->where('status', 1)
            ->orderBy('id', 'desc')
            ->chunk(100, function($orders) {
                foreach ($orders as $order) {
                    if (empty($order->number)) {
                        continue;
                    }
                    $result = EasyWechat::getApp()->payment->query($order->number);
                    if ('SUCCESS' == $result->trade_state) {
                        $order->status = 2;
                        $order->save();
                        $myWechatUpload = MyWechatUpload::firstOrNew([
                            'openid' => $order->openid,
                            'wechat_upload_id' => $order->wechat_upload_id,
                        ]);
                        $myWechatUpload->openid = $order->openid;
                        $myWechatUpload->wechat_upload_id = $order->wechat_upload_id;
                        $myWechatUpload->save();
                        echo "成功更新订单{$order->id}\r\n";

                    }
                }
            });
    }
}
